package com.kesa4j.mybatis.sql.printer;

import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.mapping.ParameterMode;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.scripting.defaults.DefaultParameterHandler;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.type.TypeHandlerRegistry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.rmi.ConnectIOException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.regex.Matcher;

@Intercepts({
        @Signature(type = StatementHandler.class, method = "query", args = {Statement.class, ResultHandler.class}),
        @Signature(type = StatementHandler.class, method = "update", args = {Statement.class}),
        @Signature(type = StatementHandler.class, method = "batch", args = {Statement.class})
})
public class SqlPrinterInterceptor implements Interceptor {
    private static final Logger log = LoggerFactory.getLogger(SqlPrinterInterceptor.class);
    private Configuration configuration = null;
    private static final ThreadLocal<SimpleDateFormat> DATE_FORMAT_THREAD_LOCAL = new ThreadLocal<SimpleDateFormat>(){
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        }
    };

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object target = invocation.getTarget();
        try {
            return invocation.proceed();
        } finally {
            String sql = getSql(target);
            log.info("SQL -> {}",sql);
        }
    }

    private String getSql(Object target) {
        try {
            StatementHandler statementHandler = (StatementHandler) target;
            BoundSql boundSql = statementHandler.getBoundSql();
            if (configuration==null) {
                final DefaultParameterHandler parameterHandler = (DefaultParameterHandler) statementHandler.getParameterHandler();
                Field field = parameterHandler.getClass().getDeclaredField("configuration");
                field.setAccessible(true);
                this.configuration = (Configuration) field.get(parameterHandler);
            }
            return formatSql(boundSql, configuration);
        } catch (Exception e) {
            log.warn("get sql error: {}", e.getLocalizedMessage());
        }
        return "";
    }

    private String formatSql(BoundSql boundSql, Configuration configuration) {
        if (configuration==null) {
            return "";
        }
        String sql = boundSql.getSql();
        if (sql==null || sql.length()==0) {
            return "";
        }
        List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
        if (parameterMappings==null) {
            return sql;
        }
        //美化sql
        sql = beautifySql(sql);
        Object parameterObject = boundSql.getParameterObject();
        TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
        for (ParameterMapping parameterMapping : parameterMappings) {
            if (parameterMapping.getMode() != ParameterMode.OUT) {
                Object value;
                String property = parameterMapping.getProperty();
                if (boundSql.hasAdditionalParameter(property)) {
                    value = boundSql.getAdditionalParameter(property);
                } else if (parameterObject == null) {
                    value = null;
                } else if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
                    value = parameterObject;
                } else {
                    MetaObject metaObject = configuration.newMetaObject(parameterObject);
                    value = metaObject.getValue(property);
                }
                String parameterValueStr = "";
                if (value instanceof String) {
                    parameterValueStr = "'" + value + "'";
                } else if (value instanceof Date) {
                    parameterValueStr = "'" + DATE_FORMAT_THREAD_LOCAL.get().format(value) + "'";
                } else {
                    parameterValueStr = String.valueOf(value);
                }
                sql = sql.replaceFirst("\\?", Matcher.quoteReplacement(parameterValueStr));
            }
        }
        return sql;
    }

    private String beautifySql(String sql) {
        return sql.replaceAll("[\\s\n ]+"," ");
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target,this);
    }

    @Override
    public void setProperties(Properties properties) {

    }
}
